package com.boot.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.boot.common.constant.AuthConstant;
import com.boot.common.vo.MemberResponseVo;
import com.boot.mall.auth.service.AuthService;
import com.boot.mall.auth.utils.HttpUtils;
import com.boot.mall.auth.vo.SocialUser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * OAuth2.0社交登录
 */
@Controller
public class OAuth2Controller {



    @Autowired
    private AuthService authService;

    /**
     * 跳转微博授权登录界面
     * @return
     */
    @GetMapping("/auth2/weibo/login")
    public String toWeiBoLogin(){
        String url = authService.getWeiBoAuthUrl();
        return "redirect:" + url;
    }

    /**
     * 用户授权之后回调的地址
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/auth2/weibo/success")
    public String loginWeiBo(@RequestParam("code") String code, HttpSession session) throws Exception {

        // 获取用户的token值
        SocialUser userToken = authService.getUserToken(code);

        // 根据用户的token值查询微博用户的基本信息
        MemberResponseVo vo = authService.getUserInfoByToken(userToken);

        if (vo == null){
            // 注册失败，返回登录页
            return "redirect:http://auth.guli.com/login.html";
        }
        // 登录成功，在session中设置登录用户信息
        session.setAttribute(AuthConstant.LOGIN_USER,vo);

        return "redirect:http://guli.com";
    }

}
